package org.jetnuke.modules.topics;

import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.entities.Stories;
import org.jetnuke.entities.Topics;

public class ShowTopics implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ShowTopics.class);

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		List ls = DataAccessDriver.getInst().newTopicsDAO()
				.selectAllOrderTopicName();// topicsPeer.doSelect(new
											// Criteria()
		// .addAscendingOrderByColumn(topicsPeer.TOPICTEXT));
		Iterator it = ls.iterator();
		HashMap topicMap = new HashMap();
		while (it.hasNext()) {
			Topics tp = (Topics) it.next();

			List all_stories = DataAccessDriver.getInst().newStoriesDAO()
					.getByTopic(tp.getTOPICID());

			// storiesPeer.doSelect(new Criteria().add(
			// storiesPeer.TOPIC, tp.getTOPICID()));
			int reads = 0;
			Iterator it_s = all_stories.iterator();
			while (it_s.hasNext()) {
				Stories st = (Stories) it_s.next();
				reads += st.getCOUNTER();
			}
			int numNews = all_stories.size();

			tp.setNumNews(numNews);
			tp.setNumReads(reads);

			List stories10 = DataAccessDriver.getInst().newStoriesDAO()
					.getStoriesByTopid_SidDesc(tp.getTOPICID(), 10);

			// storiesPeer.doSelect(new Criteria().add(
			// storiesPeer.TOPIC, tp.getTOPICID())
			// .addDescendingOrderByColumn(storiesPeer.SID).setLimit(10));
			topicMap.put(tp, stories10);
			vc.put("topicMap", topicMap);

		}
		vc.put("rows", ls);
		ActionForward returnActionForward = new ActionForward(op, info);
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return returnActionForward;
	}

}
